# -*- coding:utf-8 -*-

# @File     :handlers
# @Author   :Yupeng
# @Date     :2018/10/25 19:22
""""
针对models里面的错误，做相应的处理的方法
"""
from hte.error.models import HTEError, HTEException
from django.utils.translation import gettext as _
from django.shortcuts import render


def abort_on_error(error, error_details: (str, dict) = ''):
    """"
    如果error确实是错误对象（发生错误）则终止响应并返回json错误信息，否则什么都不做
    :param error: 检测的对象
    :param error_detail: 详细的错误信息，可以为str或dict类型
    :return: None
    :raises MGEException
    """
    if not isinstance(error, HTEError):
        return
    if error_details:
        error.error_detail = error_details
    raise HTEException(hte_error=error)


def error_page(message, title=None, detail=None, status_code=200):
    from hte.utils.middleware import GlobalRequestMiddleware
    ctx = {}
    if detail:
        ctx['detail'] = detail
    if not title:
        ctx['title'] = _('Oops')
    else:
        ctx['title'] = title
    if isinstance(message, HTEError):
        ctx['message'] = message.error_message
        status_code = message.status_code
    else:
        ctx['message'] = message
    return render(request=GlobalRequestMiddleware.get_current_request(), template_name='error.html', context=ctx, status=status_code)


def has_error(test_object):
    return isinstance(test_object, HTEError)


def error_page_404():
    return error_page(_('Resource Not Found.'), '404', status_code=404)
